package org.global.basic;

import javax.persistence.AttributeConverter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 数组类型的对象持久化
 */
public class JpaArrayPersistence {

    public static class ArrayPersistence implements AttributeConverter<String[], String> {

        @Override
        public String convertToDatabaseColumn(String[] attribute) {
            if (attribute == null || attribute.length == 0) return null;
            return String.join(",", attribute);
        }

        @Override
        public String[] convertToEntityAttribute(String dbData) {
            if (dbData == null) return null;
            return dbData.split(",");
        }
    }

    public static class ListPersistence implements AttributeConverter<List<String>, String> {

        @Override
        public String convertToDatabaseColumn(List<String> attribute) {
            if (attribute == null || attribute.isEmpty()) return "";
            return String.join(",", attribute);
        }

        @Override
        public List<String> convertToEntityAttribute(String dbData) {
            if (dbData == null) return new ArrayList<>();
            return Arrays.stream(dbData.split(",")).collect(Collectors.toList());
        }
    }
}
